package cn.bone.auth.security.base.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.UUID;

public class JWTUtil {

    /*获取随机字符串*/
    private static String createJTI(){
        byte[] bytes = UUID.randomUUID().toString().getBytes();
        byte[] encode = Base64.getEncoder().encode(bytes);
        String result = new String(encode);
        return result;
    }


    /*私钥加密*/
    public static String createToken(JJWTPayload jjwtPayload, PrivateKey privateKey){
        return Jwts.builder()
                .claim("userId", jjwtPayload.getUserId())
                .claim("loginTime", jjwtPayload.getLoginTime())
                .claim("userType", jjwtPayload.getUserType())
                .claim("origin", jjwtPayload.getOrigin())
                .setId(createJTI())
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();

    }

    /*公钥解密*/
    public static JJWTPayload getInfoFormToken(String token, PublicKey publicKey){
        Jws<Claims> claimsJws = Jwts.parserBuilder()
                .setSigningKey(publicKey)
                .build()
                .parseClaimsJws(token);
        Claims body = claimsJws.getBody();

        Integer userId = body.get("userId", Integer.class);
        Long loginTime = body.get("loginTime", Long.class);
        String userType = body.get("userType", String.class);
        String origin = body.get("origin", String.class);

        JJWTPayload jjwtPayload = new JJWTPayload();
        jjwtPayload.setUserId(userId);
        jjwtPayload.setLoginTime(loginTime);
        jjwtPayload.setUserType(userType);
        jjwtPayload.setOrigin(origin);
        return jjwtPayload;
    }


    @Data
    public static class JJWTPayload{
        private Integer userId;
        private Long loginTime;
        private String userType;
        private String origin;
    }
}
